package com.heima.wemedia.interceptors;

import com.heima.common.threadlocal.UserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    /**
     * 从请求头获取userId
     * 放入Theadlocal中
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//      从请求头获取userId
        String userId = request.getHeader("userId");
        if(StringUtils.isBlank(userId)){
//            请求头没有用户信息，结束请求
            log.error("请求头没有用户信息");
            return false;
        }
//        放入Theadlocal中
        UserThreadLocalUtils.setUserId(Integer.valueOf(userId));
        log.info("拦截器放行，userId={}",userId);
        return true;
    }

    /**
     * 清除threalocal中的数据
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocalUtils.removeUser();
    }
}
